package com.lge.qcontact.members;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.lge.qcontact.MainActivity;
import com.lge.qcontact.R;
import com.lge.qcontact.threads.RegistAccountThread;
import com.lge.qcontact.utils.MUtils;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class RegistMemberActivity extends Activity {
	// MainActivity에서 등록으로 넘어온 ID/PW값을 가지고 기본 ID/PW 필드를 자동으로 채워준다.
	// ID중복 체크 버튼을 누르면 server DB에서 ID를 검색하여 중복체크를 한다.
	// 중복 ID가 있으면 EditText.setError()를 이용하여 에러를 출력한다.
	// ID중복 체크를 하지 않은 경우 등록버튼을 누르면 토스트 메시지를 띄워주고, 화면 전환이 되지 않는다.
	// PW확인을 하여 일치하는 경우 등록한다.
	// 취소 버튼을 누르면 이 activity를 종료하여 이전 화면으로 돌아간다.
	// 연락처 추가 버튼을 누르면 mobile, e-mail, phone 항목을 입력할 수 있는 필드를 화면에 추가하여
	// 입력받을 수 있도록 한다.

	private EditText id_regist, pw_regist, pw_confirm_regist, name_regist,
			mobile_regist, email_regist, phone_number_regist, group_regist;
	private Button regist_check_duplicateId, regist_check_duplicateGroup,
			regist_ok_button, regist_cancel_button;

	View focusView = null;
	private boolean checkDuplicateId = false;

	private boolean checkedDuplicateId = false;
	private boolean validId = true;

	private boolean pwConfirm = false;

	private boolean checkDuplicateGroup = false;
	private boolean checkedDuplicateGroup = false;

	private String tempId = null;
	private String tempGroup = null;

	private SearchIdThread iThread;
	private SearchGroupThread gThread;

	private String resultUpload = null;

	private GroupThread gThread2;
	private ListView listView;
	static ArrayList<String> list;
	IconAdapter mAdapter;

	private Handler idHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Bundle result = msg.getData();
			Log.i("idHandler", "checkDuplicateId :" + checkDuplicateId);
			if (id_regist.getText().length() == 0) {
				MUtils.toast(RegistMemberActivity.this, "아이디를 입력해주세요.");
				id_regist.setError(getString(R.string.error_field_required));
				focusView = id_regist;
				Log.i("IDCHECK", "1");
			} else if (checkDuplicateId) {
				MUtils.toast(RegistMemberActivity.this, "이미 사용 중인 아이디입니다.");
				id_regist.setError("이미 사용 중인 아이디입니다.");
				focusView = id_regist;
				Log.i("IDCHECK", "2");
			} else if (id_regist.getText().length() > 0) {
				String id = id_regist.getText().toString();
				Log.i("IDCHECK", "3");
				for (int i = 0; i < id_regist.getText().length(); i++) {
					Log.i("IDCHECK", "for " + validId);
					if (id.charAt(i) >= '0' && id.charAt(i) <= '9') {
						validId = true;
						continue;
					} else if (id.charAt(i) >= 'A' && id.charAt(i) <= 'Z') {
						validId = true;
						continue;
					} else if (id.charAt(i) >= 'a' && id.charAt(i) <= 'z') {
						validId = true;
						continue;
					} else if (id.charAt(i) == '.') {
						validId = true;
						continue;
					} else {
						MUtils.toast(RegistMemberActivity.this,
								"글자(a-z), 숫자 및 마침표만 사용하시기 바랍니다.");
						id_regist.setError("글자(a-z), 숫자 및 마침표만 사용하시기 바랍니다.");
						focusView = id_regist;
						validId = false;
						break;
					}
				}
				Log.i("IDCHECK", "4 " + validId);
			}
			if (!checkDuplicateId && validId
					&& (id_regist.getText().length() > 0)) {
				Log.i("IDCHECK", "5");
				MUtils.toast(RegistMemberActivity.this, "사용 가능한 아이디입니다.");
				id_regist.setError(null);
			}

			if (!checkDuplicateId && validId) {
				checkedDuplicateId = true;
			} else
				checkedDuplicateId = false;
		}

	};

	private Handler groupHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			Bundle result = msg.getData();
			Log.i("RESULTg:", checkDuplicateGroup + "");
			if (group_regist.getText().length() == 0) {
				MUtils.toast(RegistMemberActivity.this, "그룹을 입력해주세요.");
				group_regist.setError(getString(R.string.error_field_required));
				focusView = group_regist;
			} else if (checkDuplicateGroup) {
				MUtils.toast(RegistMemberActivity.this, "존재하는 그룹입니다, \""
						+ group_regist.getText().toString() + "\" 그룹에 등록됩니다.");
				group_regist.setError(null);
				checkDuplicateGroup = true;
			} else if (group_regist.getText().length() > 0) {
//				MUtils.toast(RegistMemberActivity.this,
//						"존재하지 않는 그룹입니다, 등록시 새 그룹이 생성됩니다.");
//				group_regist.setError("등록시 새 그룹이 생성됩니다.");
				group_regist.setError(null);
				checkDuplicateGroup = false;
//				focusView = group_regist;
			}

//			checkedDuplicateGroup = true;
		}
	};

	private Handler registHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {

			Bundle result = msg.getData();
			resultUpload = result.getString("upload");
			Log.i("upload", resultUpload + "");
			try {
				URL url = new URL(resultUpload.toString());
				url.openStream();
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	};

	private Handler groupHandler2 = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			Bundle result = msg.getData();
			list.add(result.getString("groupName"));
			mAdapter.notifyDataSetChanged();
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == event.KEYCODE_BACK) {
			finish();
			Intent intent = new Intent(RegistMemberActivity.this,
					MainActivity.class);
			startActivity(intent);
			return false;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
				.detectDiskReads().detectDiskWrites().detectNetwork()
				.penaltyLog().build());
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_regist_member);

		id_regist = (EditText) findViewById(R.id.id_regist);
		pw_regist = (EditText) findViewById(R.id.pw_regist);
		pw_confirm_regist = (EditText) findViewById(R.id.pw_confirm_regist);
		name_regist = (EditText) findViewById(R.id.name_regist);
		mobile_regist = (EditText) findViewById(R.id.mobile_regist);
		email_regist = (EditText) findViewById(R.id.email_regist);
		phone_number_regist = (EditText) findViewById(R.id.phone_number_regist);
		group_regist = (EditText) findViewById(R.id.group_regist);

		regist_check_duplicateId = (Button) findViewById(R.id.regist_check_duplicateId);
		regist_check_duplicateGroup = (Button) findViewById(R.id.regist_check_duplicateGroup);
		regist_ok_button = (Button) findViewById(R.id.regist_ok_button);
		regist_cancel_button = (Button) findViewById(R.id.regist_cancel_button);

		Intent intent = getIntent();
		String uid = intent.getExtras().get("uid").toString();
		id_regist.setText(uid);

		id_regist.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				checkedDuplicateId = false;
				checkDuplicateId = false;
				Log.i("FLAG", checkDuplicateId + " " + checkedDuplicateId);
				if (id_regist.getText().length() > 0) {
					String id = id_regist.getText().toString();
					for (int i = 0; i < id_regist.getText().length() - 1; i++) {
						if (id.charAt(i) >= '0' && id.charAt(i) <= '9')
							continue;
						else if (id.charAt(i) >= 'A' && id.charAt(i) <= 'Z')
							continue;
						else if (id.charAt(i) >= 'a' && id.charAt(i) <= 'z')
							continue;
						else if (id.charAt(i) == '.')
							continue;
						else {
							id_regist
									.setError("글자(a-z), 숫자 및 마침표만 사용하시기 바랍니다.");
							focusView = id_regist;
							break;
						}
					}
				}
			}

		});

		group_regist.addTextChangedListener(new TextWatcher() {

			@Override
			public void afterTextChanged(Editable arg0) {
			}

			@Override
			public void beforeTextChanged(CharSequence arg0, int arg1,
					int arg2, int arg3) {
			}

			@Override
			public void onTextChanged(CharSequence arg0, int arg1, int arg2,
					int arg3) {
				checkedDuplicateGroup = false;
				checkDuplicateGroup = false;
				Log.i("FLAG", checkDuplicateGroup + " " + checkedDuplicateGroup);
			}

		});

		regist_check_duplicateId.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				iThread = new SearchIdThread(idHandler);
				iThread.setDaemon(true);
				iThread.start();
			}
		});

		regist_check_duplicateGroup
				.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View arg0) {
						CustomDialog CustomDialog = new CustomDialog(
								RegistMemberActivity.this);
						CustomDialog.show();
					}
				});

		regist_ok_button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {

				pwConfirm = pw_regist.getText().toString()
						.equals(pw_confirm_regist.getText().toString());
				if (!checkedDuplicateId || !validId) {
					MUtils.toast(RegistMemberActivity.this, "ID 중복체크를 해주세요.");
					id_regist.setError("ID 중복체크를 해주세요.");
					focusView = id_regist;
				} else if (pw_regist.getText().toString().length() < 4) {
					MUtils.toast(RegistMemberActivity.this,
							"PASSWORD는 4자리 이상 입력하세요.");
					pw_regist.setError("PASSWORD는 4자리 이상 입력하세요.");
					focusView = pw_regist;
				} else if (!pwConfirm) {
					MUtils.toast(RegistMemberActivity.this,
							"PASSWORD가 일치하지 않습니다.");
					pw_confirm_regist.setError("PASSWORD가 일치하지 않습니다.");
					focusView = pw_confirm_regist;
				} else if (name_regist.getText().length() == 0) {
					MUtils.toast(RegistMemberActivity.this, "이름을 입력해주세요.");
					name_regist
							.setError(getString(R.string.error_field_required));
					focusView = name_regist;
				} else if (email_regist.getText().length() == 0) {
					MUtils.toast(RegistMemberActivity.this, "이메일 주소를 입력해주세요.");
					email_regist
							.setError(getString(R.string.error_field_required));
					focusView = email_regist;
				} else if (mobile_regist.getText().length() == 0) {
					MUtils.toast(RegistMemberActivity.this, "휴대폰 번호를 입력해주세요.");
					mobile_regist
							.setError(getString(R.string.error_field_required));
					focusView = mobile_regist;
				} else if (phone_number_regist.getText().length() == 0) {
					MUtils.toast(RegistMemberActivity.this, "전화번호를 입력해주세요.");
					phone_number_regist
							.setError(getString(R.string.error_field_required));
					focusView = phone_number_regist;
				} else if (group_regist.getText().length() == 0) {
					MUtils.toast(RegistMemberActivity.this, "그룹을 입력해주세요.");
					group_regist
							.setError(getString(R.string.error_field_required));
					focusView = group_regist;
				} else if (!checkedDuplicateGroup) {
					MUtils.toast(RegistMemberActivity.this, "그룹선택을 해주세요.");
					group_regist.setError("그룹선택을 해주세요.");
					focusView = group_regist;
				} else if (pwConfirm && checkedDuplicateId
						&& (pw_regist.getText().toString().length() >= 4)
						&& checkedDuplicateGroup) {

					String ismaster;
					if (checkDuplicateGroup)
						ismaster = "false";
					else
						ismaster = "true";

					RegistAccountThread rThread = new RegistAccountThread(
							registHandler, id_regist.getText().toString(),
							pw_regist.getText().toString(), name_regist
									.getText().toString(), email_regist
									.getText().toString(), mobile_regist
									.getText().toString(), phone_number_regist
									.getText().toString(), group_regist
									.getText().toString(), ismaster);
					rThread.setDaemon(true);
					rThread.start();

					Intent regIntent = new Intent(RegistMemberActivity.this,
							MainActivity.class);
					regIntent.putExtra("uid", id_regist.getText());
					startActivity(regIntent);
					finish();
				}
			}
		});

		regist_cancel_button.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				finish();
				Intent intent = new Intent(RegistMemberActivity.this,
						MainActivity.class);
				startActivity(intent);
			}
		});
	}

	class SearchIdThread extends Thread {
		Handler idHandler;
		String tag = null;

		public SearchIdThread(Handler handler) {
			idHandler = handler;
		}

		public void run() {

			try {
				URL url = new URL(
						"http://192.168.0.205:8080/com.lg.project.myexample.cmd.RetrieveMemberUserJoinListCmd.vcc");

				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(url.openStream(), "utf-8");

				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {
					Log.i("CHECK1", "checkDuplicateId: " + checkDuplicateId);
					if (checkDuplicateId)
						break;
					tag = parser.getName();
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						break;
					case XmlPullParser.START_TAG:
						if (tag.equals("uid")) {
							tempId = parser.nextText();
							if (tempId.equals(id_regist.getText().toString())) {
								checkDuplicateId = true;
								Log.i("CHECK1", "checkDuplicateId: "
										+ checkDuplicateId);
								break;
							}
						}
						break;
					case XmlPullParser.END_TAG:
						break;
					}
					eventType = parser.next();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			Message msg = Message.obtain();
			Bundle data = new Bundle();
			data.putBoolean("checkDuplicateId", checkDuplicateId);
			msg.setData(data);
			idHandler.sendMessage(msg);
			Log.i("IDTHREADCHECK", "checkDuplicateId: " + checkDuplicateId
					+ "checkedDuplicateId: " + checkedDuplicateId);
			// try {
			// // Thread.sleep(500);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
		}
	}

	class SearchGroupThread extends Thread {
		Handler groupHandler;
		String tag = null;

		public SearchGroupThread(Handler handler) {
			groupHandler = handler;
		}

		public void run() {

			try {
				URL url = new URL(
						"http://192.168.0.205:8080/com.lg.project.myexample.cmd.RetrieveMemberUserJoinListCmd.vcc");

				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(url.openStream(), "utf-8");

				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {
					Log.i("CHECK2", "checkDuplicateGroup: "
							+ checkDuplicateGroup);
					if (checkDuplicateGroup)
						break;
					tag = parser.getName();
					switch (eventType) {
					case XmlPullParser.START_DOCUMENT:
						break;
					case XmlPullParser.START_TAG:
						if (tag.equals("gname")) {
							tempGroup = parser.nextText();
							if (tempGroup.equals(group_regist.getText()
									.toString())) {
								checkDuplicateGroup = true;
								break;
							}
						}
						break;
					case XmlPullParser.END_TAG:
						break;
					}
					eventType = parser.next();
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			Message msg = Message.obtain();
			Bundle data = new Bundle();
			data.putBoolean("checkDuplicateGroup", checkDuplicateGroup);
			msg.setData(data);
			groupHandler.sendMessage(msg);
			Log.i("CHECK", "checkDuplicateGroup: " + checkDuplicateGroup);
			// try {
			// // Thread.sleep(500);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
		}
	}

	class CustomDialog extends Dialog implements OnClickListener {
		EditText name;
		EditText number;
		Button okButton;
		Button cancelButton;
		Context mContext;

		public CustomDialog(Context context) {
			super(context);
			mContext = context;
			/** 'Window.FEATURE_NO_TITLE' - Used to hide the title */
			requestWindowFeature(Window.FEATURE_NO_TITLE);
			setContentView(R.layout.dialog);

			okButton = (Button) findViewById(R.id.button1);
			cancelButton = (Button) findViewById(R.id.button2);
			okButton.setOnClickListener(this);
			cancelButton.setOnClickListener(this);

			list = new ArrayList<String>();
			list.add("직접 입력");
			gThread2 = new GroupThread(groupHandler2);
			gThread2.setDaemon(true);
			gThread2.start();

			listView = (ListView) findViewById(R.id.listView);
			mAdapter = new IconAdapter(RegistMemberActivity.this);
			listView.setAdapter(mAdapter);

			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> listview, View view,
						int position, long id) {
					if (position == 0) {
						gThread = new SearchGroupThread(groupHandler);
						gThread.setDaemon(true);
						gThread.start();
						checkDuplicateGroup = false;
					} else {
						group_regist.setText(list.get(position));
						checkDuplicateGroup = true;
					}
					checkedDuplicateGroup = true;
					group_regist.setError(null);
					dismiss();
				}
			});

		}

		@Override
		public void onClick(View v) {
			if (v == okButton) {
				if (TextUtils.isEmpty(name.getText())) {
					MUtils.toast(RegistMemberActivity.this, "empty");
				} else {
					MUtils.toast(RegistMemberActivity.this, "ok");
					dismiss();
				}

			} else if (v == cancelButton) {
				dismiss();
			}
		}

	}

	class GroupThread extends Thread {

		Handler groupHandler2;
		String tag = null;

		String tempGroupName = null;

		public GroupThread(Handler handler) {
			groupHandler2 = handler;
		}

		public void run() {

			try {
				URL url = new URL(
						"http://192.168.0.205:8080/com.lg.project.myexample.cmd.RetrieveCmd.vcc?param=user_info,ismaster,true");

				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				XmlPullParser parser = factory.newPullParser();
				parser.setInput(url.openStream(), "utf-8");

				int eventType = parser.getEventType();
				while (eventType != XmlPullParser.END_DOCUMENT) {

					switch (eventType) {

					case XmlPullParser.START_DOCUMENT:
						break;
					case XmlPullParser.START_TAG:
						if (parser.getName().equals("gname")) {
							tempGroupName = parser.nextText();
							Message msg = Message.obtain();
							Bundle data = new Bundle();
							data.putString("groupName", tempGroupName);
							msg.setData(data);
							groupHandler2.sendMessage(msg);
						}
						break;
					case XmlPullParser.END_TAG:
						break;
					}

					eventType = parser.next();
				}

			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

	}

	class IconAdapter extends BaseAdapter {

		private Activity mContext;

		public IconAdapter(Activity mContext) {
			this.mContext = mContext;

		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return RegistMemberActivity.list.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View row = convertView;

			if (row == null) {
				LayoutInflater inflater = mContext.getLayoutInflater();
				row = inflater.inflate(R.layout.activity_custom_row, null);
			}

			TextView label = (TextView) row.findViewById(R.id.group);
			label.setText(RegistMemberActivity.list.get(position));

			return row;
		}
	}

}
